<template>
	<div class="app-container">
		<el-form class="" @submit.native.prevent :model="form" ref="queryRef" :rules="rules" :inline="true"
			label-width="106">
			<div class="bgWhite radius8 pt25">
				<div class="pl30 fb fs16 border-bottom pb25 mb30">
					毛利率计算器
				</div>
				<div>
					<div class="flex col-center row-between plr30 border-bottom pb10">
						<div class="flex col-center">
							<div>
								<span class="color-red">*</span>
								<span class="fb mr20">关联商品</span>
							</div>
							<!-- <span class="flex col-center cursor main-color fs14" @click="countPriceGoods()">
								点击预估订单收益
							</span> -->
						</div>
						<el-button class="mt5" type="defaultBtn" @click="handleAdd(0)">添加商品</el-button>
					</div>
					<div class="flex col-center row-end mt15 mr20">
						<div class="fs14 mr20 color2">
							<span class="mr10">请选择省份</span>
							<el-cascader v-model="addressNode" ref="cascader" style="width:248px;" :props="address"
								@change="handleChangeAddress" size="large">
							</el-cascader>
						</div>
						<div class="fs14 mr20 color2">
							<span class="mr10">物流</span>
							<el-select v-model="logisticsId" placeholder="请选择" 
							clearable
							size="large" style="width: 248px;" @change="logChange">
								<el-option v-for="dict in logListArr" :key="dict.id" :label="dict.logisticsCompany"
									:value="dict.id" />
							</el-select>
						</div>
					</div>
					<div class="plr30 mt20">
						<el-table :data="form.goods" style="width: 100%;text-align: center;"
							:cell-style="{ textAlign: 'center','line-height':'54px'}"
							:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }"
							:summary-method="getSummaries" show-summary>
							<el-table-column prop="commodityName" label="商品名称" width="150px" />
							<el-table-column prop="commodityCode" label="商品编码" width="150px" />
							<el-table-column prop="specificationId" label="商品规格">
								<template v-slot="scope">
									<dict-tag :options="bus_product_specification_unit"
										:value="scope.row.specificationId" />
								</template>
							</el-table-column>
							<el-table-column label="库存单价" width="200">
								<template #default="scope">
									<el-select placeholder="请选择" size="large" style="width: 188px"
										v-model="scope.row.unitSinglePrice"
										@change="unitSinglePriceChange(0,scope.$index)">
										<el-option v-for="item in scope.row.countSelectPrice" :key="item.value"
											:label="item.label" :value="item.value" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column label="销售单价（元）" width="200px">
								<template #default="scope">
									<el-form-item :prop="'commodityList.' + scope.$index + '.unitPrice'"
										style="margin-right: 0;margin-top: 18px;">
										<el-input type="number" min="0" v-model="scope.row.unitPrice"
											style="width: 120px" size="large"
											@input="unitPriceChange(scope.row.unitPrice,scope.$index)"
											placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="quantity" label="数量" width="200px">
								<template #default="scope">
									<el-form-item :prop="'commodityList.' + scope.$index + '.quantity'"
										style="margin-right: 0;margin-top: 18px;">
										<el-input type="number" min="1" v-model="scope.row.quantity"
											style="width: 120px" size="large" @input="quantityChange(0,scope.$index)"
											placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="numberOfShippingBoxes" label="箱数量" width="150px">
								<template v-slot="scope">
									<div>
										<el-input type="number" min="0" v-model="scope.row.numberOfShippingBoxes"
											@input="numberOfShippingBoxesChange(1,scope.$index)" size="large"
											placeholder="请输入" />
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="date" label="总价（元）" width="150px">
								<template #default="scope">
									{{(scope.row.unitPrice*1*scope.row.quantity*1).toFixed(2)}}
								</template>
							</el-table-column>
							<el-table-column fixed="right" label="操作" align="center" width="100px"
								class-name="small-padding fixed-width">
								<template #default="scope">
									<el-button link style="color: red!important;" type="primary"
										@click="delGoods(scope.$index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					 <!-- v-if="isCanGift == true" -->
					<div>
						<div class="flex col-center row-between plr30 border-bottom pb10 mt30">
							<div>
								<span class="color-red"></span>
								<span class="fb mr20">赠品管理</span>
							</div>
							<el-form class="  " :model="form" ref="queryRef" :inline="true">
								<el-button class="mt5" type="defaultBtn" @click="handleAdd(1)">添加赠品</el-button>
							</el-form>
						</div>
						<div class="plr30 mt20 pb30">
							<el-table :data="form.gift" style="width: 100%"
								:cell-style="{ textAlign: 'center','line-height':'54px'}"
								:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }">
								<el-table-column prop="commodityName" label="商品名称" width="150px" />
								<el-table-column prop="commodityCode" label="商品编码" width="150px" />
								<el-table-column prop="specificationId" label="商品规格">
									<template v-slot="scope">
										<dict-tag :options="bus_product_specification_unit"
											:value="scope.row.specificationId" />
									</template>
								</el-table-column>
								<el-table-column label="库存单价" width="200">
									<template #default="scope">
										<el-select disabled placeholder="请选择" size="large" style="width: 188px"
											v-model="scope.row.unitSinglePrice"
											@change="unitSinglePriceChange(1,scope.$index)">
											<el-option v-for="item in scope.row.countSelectPrice" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column label="销售单价（元）" width="200px">
									<template #default="scope">
										<el-form-item :prop="'commodityList.' + scope.$index + '.unitPrice'"
											style="margin-right: 0;margin-top: 18px;">
											<el-input type="number" min="0" disabled v-model="scope.row.unitPrice"
												style="width: 120px" size="large"
												@input="unitPriceChange1(scope.row.unitPrice,scope.$index)"
												:min="scope.row.factoryPrice" placeholder="请输入" />
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="quantity" label="数量" width="200px">
									<template #default="scope">
										<el-form-item :prop="'commodityList.' + scope.$index + '.quantity'"
											style="margin-right: 0;margin-top: 18px;">
											<el-input type="number" min="1" v-model="scope.row.quantity"
												style="width: 120px" size="large"
												@input="quantityChange1(1,scope.$index)" placeholder="请输入" />
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="numberOfShippingBoxes" label="箱数量" width="150px">
									<template v-slot="scope">
										<div>
											<el-input type="number" min="0" v-model="scope.row.numberOfShippingBoxes"
												@input="numberOfShippingBoxesChange(2,scope.$index)" size="large"
												placeholder="请输入" />
										</div>
									</template>
								</el-table-column>
								<el-table-column prop="date" label="总价（元）" width="150px">
									<template #default="scope">
										{{(scope.row.unitPrice*1*scope.row.quantity*1).toFixed(2)}}
									</template>
								</el-table-column>
								<el-table-column fixed="right" label="操作" align="center" width="100px"
									class-name="small-padding fixed-width">
									<template #default="scope">
										<el-button link style="color: red!important;" type="primary"
											@click="delGift(scope.$index)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
					<div class="text-center pb30 pt20">
						<el-button class="mt5" type="defaultBtn" @click="countRate">计算毛利率</el-button>
					</div>
				</div>
			</div>
		</el-form>
		<el-dialog title="计算结果" v-model="dialogVisible" width="670px" center class="radius8" :before-close="close">
			<div class="mt15 pb15">
				<el-table :data="result" style="width: 100%"
					:cell-style="{ textAlign: 'center','line-height':'54px','color':'#333'}"
					:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }">
					<el-table-column prop="orderTotalAmount" label="订单金额" />
					<el-table-column prop="inventoryCosts" label="库存成本" />
					<el-table-column prop="realTimeCosts" label="实时成本" />
					<el-table-column prop="inventoryGrossProfitRate" label="库存毛利率" />
					<el-table-column prop="realTimeProfitRate" label="实时毛利率" />
				</el-table>
			</div>
		</el-dialog>
		<!-- 添加商品 -->
		<addGoodsList ref="goodsPop" @getGoods="selectGoods" :idArr="idsGoodsArr"></addGoodsList>
		<!-- 添加赠品 -->
		<addGiftList ref="giftPop" @getGift="selectGift" :idArr="idsGiftArr"></addGiftList>
	</div>
</template>

<script>
	import {
		fnRoyalties, //计算提成
		fnCommodity, //计算商品箱数
		conversion //获取商品折算价格
	} from "@/api/business/order";
	import {
		getGoodsGroup, //查询商品组
	} from "@/api/business/product";
	import {
		fnGrossProfitRate
	} from '@/api/business/tool'
	import {
		list 
	} from "@/api/business/rules_logistics";//物流
	import {
		getDivisions //省市区
	} from "@/api/business/opportunity";
	import addGoodsList from '@/components/addGoods/index.vue' //添加商品
	import addGiftList from '@/components/addGift/index.vue' //添加赠品
	export default {
		components: {
			addGoodsList,
			addGiftList
		},
		data() {
			return {
				orderTotalAmount:'',//订单总金额
				dialogVisible: false,
				result: [{
					orderTotalAmount: '100'
				}],
				bus_product_specification_unit: this.useDict('bus_product_specification_unit')
					.bus_product_specification_unit,
				form: {
					goodsId: [],
					goods: [],
					giftIds: [],
					gift: []
				},
				rules: {
					quantity: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					unitPrice1: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					quantity2: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					unitPrice2: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ]
				},
				yjPrice:0,
				hjPrice: 0,
				getForm: '', //获取到的存储form
				idsGoodsArr: [], //已经选择的商品id
				idsGiftArr: [], //已选择赠品id
				isCanGift: false, //是否可以添加赠品
				obj: {},
				areaCode: '11', //地区编码-默认北京
				logisticsId: '', //物流id
				logListArr:[],//物流arr
				addressNode: ['11'],//-默认北京
				address: {
					lazy: true,
					lazyLoad(node, resolve) {
						setTimeout(() => {
							const nodes = [];
							// 构造查询条件
							let query = {
								id: node.level == 0 ? 0 : node.value,
								level: node.level + 1,
								type: 'provinces',
								pCode: node.value,
								pageNum: 1,
								pageSize: 5000
							}
							if (query.level == 2) {
								query.type = 'cities';
								// form.customerAddress = node.label;
							}
							if (query.level == 3) {
								query.type = 'areas';
							}
							if (query.level == 4) {
								query.type = 'streets';
							}
							//查询接口
							getDivisions(query, query.type).then(res => {
								res.rows.map((item) => {
									let obj = {
										value: item.code,
										label: item.name,
										pCode: item.pCode,
										leaf: query.level >= 1
										//leaf: item.hasChildren // 节点级别，如果没有子节点就停止查询
									}
									nodes.push(obj);
								})
								//重新加载节点
				
								resolve(nodes);
							})
						}, 100);
					}
				},
			}
		},
		created() {
			this.getForm = localStorage.getItem('form')
			if (this.getForm) {
				this.form = JSON.parse(this.getForm)
			}
			this.getDivisionsList()
			this.getChoose()
		},
		methods: {
			// 选择地址
			handleChangeAddress(e) {
				let nodesObj = this.$refs["cascader"].getCheckedNodes()[0].pathLabels;
				this.areaCode = this.addressNode[0]
				console.log(this.areaCode,'addressNode')
			},
			// 物流
			getDivisionsList(){
				let data = {
					pageNum: 1,
					pageSize: 200,
					level: 2,
					channel: "1001",
					type: "provinces"
				}
				list(data).then((response) => {
					this.logListArr = response.rows;
				});
			},
			// 物流切换
			logChange(e){
				for(let key in this.logListArr){
					if(this.logListArr[key].id == e){
						// this.logistics = this.logListArr[key].logisticsCompany
					}
				}
			},
			// 添加商品 / 赠品
			handleAdd(num) {
				if (num == 0) {
					let arr = []
					if (this.form.goods.length > 0) {
						for (let key in this.form.goods) {
							arr.push(this.form.goods[key].commodityId)
						}
					} else {
						arr = []
					}
					this.idsGoodsArr = arr
					this.$refs.goodsPop.open()
				} else {
					let arr1 = []
					if (this.form.gift.length > 0) {
						for (let key in this.form.gift) {
							arr1.push(this.form.gift[key].commodityId)
						}
					} else {
						arr1 = []
					}
					this.idsGiftArr = arr1
					this.$refs.giftPop.open()
				}
			},
			//添加商品最后一行自定义
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index == 7) {
						sums[index] = '合计：' + this.hjPrice;
					}
				});
				return sums;
			},
			getChoose() {
				// 选中的商品信息
				this.goodsId = localStorage.getItem('goodsId') ? JSON.parse(localStorage.getItem('goodsId')) : []
				if (this.goodsId.length > 0) {
					let a = 0
					for (let key in this.goodsId) {
						for (let j in this.form.goods) {
							if (this.goodsId[key] == this.form.goods[j].commodityId) {
								a += 1
							}
						}
					}
					if (a != this.goodsId.length) {
						this.getGoodsGroupList(this.goodsId.join(','), 0)
					}

				}
				//选中赠品信息
				this.giftIds = localStorage.getItem('giftIds') ? JSON.parse(localStorage.getItem('giftIds')) : []
				if (this.giftIds.length > 0) {
					console.log(this.giftIds, 'this.giftIds')
					let b = 0
					for (let key in this.giftIds) {
						for (let j in this.form.gift) {
							if (this.giftIds[key] == this.form.gift[j].commodityId) {
								b += 1
							}
						}
					}
					if (b != this.giftIds.length) {
						this.getGoodsGroupList(this.giftIds.join(','), 1)
					}
				}
				this.countPrice()
			},
			//选中的商品
			selectGoods(e) {
				let getValue
				for(let key in this.form.goods){
					for(let j in e){
						if(this.form.goods[key].commodityId == e[j]){
							e.splice(j,1)
						}
					}
				}
				getValue = e
				this.getGoodsGroupList(e, 0)
			},
			// 关联商品查询
			getGoodsGroupList(ids, num) {
				// num:0商品  1赠品
				let deptId = JSON.parse(localStorage.getItem('user')).deptId
				let queryParams = {
					deptId: deptId
				}
				getGoodsGroup(ids, queryParams).then((response) => {
					let selectList = response.data
					this.goodsHandle(selectList, num, ids)
				})
			},
			//商品信息处理
			goodsHandle(selectList, num, ids) {
				if (selectList.length > 0) {
					let arr = []
					for (let i in selectList) {
						let item = {
							type: num, //类型（0=商品，1=赠品）
							commodityId: selectList[i].id, //商品id
							commoditySpecification: selectList[i].specificationId, //商品规格
							factoryPrice: selectList[i].offlinePrices[0].factoryPrice, //出厂价
							unitPrice: num == 0 ? selectList[i].offlinePrices[0].onlineUnitPrice : 0, //销售单价（元）
							quantity: '1', //数量
							subtotal: '', //小计
							classifyId: selectList[i].classifyId, //分类id
							commodityType: selectList[i].commodityType, //产品类型正常品，试验品促销品
							commodityNumber: selectList[i].commodityNumber, //商品编码
							productId: selectList[i].productId, //关联产品id
							specificationId: selectList[i].specificationId, //关联规格ID
							commodityName: selectList[i].commodityName, //商品名称
							commodityCode: selectList[i].commodityCode, //商品Code码
							minUnit: selectList[i].minUnit, //最小单位
							caseQuantity: selectList[i].caseQuantity, //整件数量
							unitContent: selectList[i].unitContent, //单位含量
							contentUnit: selectList[i].contentUnit, //含量单位（数据字典）
							mainImageUrl: selectList[i].mainImageUrl, //商品主图URL
							onlineUnitPrice: selectList[i].onlineUnitPrice, //线上拆箱单价
							caseUnitPrice: selectList[i].caseUnitPrice, //整件单价
							tonPrice: selectList[i].tonPrice, //吨价
							numberOfShippingBoxes: selectList[i].numberOfShippingBoxes, //箱数量
							boxConversionUnitPrice: selectList[i].boxConversionUnitPrice,
							tonConversionUnitPrice: selectList[i].tonConversionUnitPrice,
							commissionRatio:selectList[i].commission,//提成比率
							unitSinglePrice: 0
						}
						arr.push(item)
					}
					if (num == 0) {
						for (let k in this.form.goods) {
							for (let j in arr) {
								if (this.form.goods[k].commodityId == arr[j].commodityId) {
									arr.splice(j, 1)
								}
							}
						}
						this.form.goods = this.form.goods.concat(arr)
						this.conversion(ids.join(','), 0)
					} else {
						for (let k in this.form.gift) {
							for (let j in arr) {
								if (this.form.gift[k].commodityId == arr[j].commodityId) {
									arr.splice(j, 1)
								}
							}
						}
						this.form.gift = this.form.gift.concat(arr)
						this.conversion(ids.join(','), 1)
					}
					this.$forceUpdate()
				}
				
			},
			// 计算商品折算价格
			conversion(ids, num) {
				let data = {
					ids: ids
				}
				conversion(data).then(res => {
					
					let data_ = res.data
					let nestedObjects = []
					let arrList = []
					if (num == 0) {
						arrList = this.form.goods
					} else if (num == 1) {
						arrList = this.form.gift
					} else {
						arrList = this.form.goods.concat(this.form.gift)
					}
					
					let getIds = ids.split(',')
					for (const item of data_) {
						this.obj[Object.keys(item)] = Object.values(item)[0]
					}
					if(num == 0 || num == 1){
						for (let key in arrList) {
							for(let m in getIds){
								if(getIds[m] == arrList[key].commodityId){
									if(arrList[key].type == 0){
										arrList[key].factoryPrice = this.obj[arrList[key].commodityId].price.unitPrice
										arrList[key].countSelectPrice = [{
													value: 0,
													label: '单价：' + this.obj[arrList[key].commodityId].price.unitPrice + '元'
												},
												{
													value: 1,
													label: '折箱单价：' + this.obj[arrList[key].commodityId].price
														.boxConversionUnitPrice + '元'
												},
												{
													value: 2,
													label: '折吨单价：' + this.obj[arrList[key].commodityId].price.tonConversionUnitPrice + '元'
												}
											]
											 arrList[key].unitPrice = this.obj[arrList[key].commodityId].price.unitPrice
									}else{	
										arrList[key].factoryPrice = this.obj[arrList[key].commodityId].price.boxConversionUnitPrice
										arrList[key].countSelectPrice = [
												{
													value: 0,
													label: '折箱单价：' + this.obj[arrList[key].commodityId].price.boxConversionUnitPrice + '元'
												}
											]
											 arrList[key].unitPrice = 0
									}
							
									arrList[key].conPrice = this.obj[arrList[key].commodityId].price
									arrList[key].conQuantity = this.obj[arrList[key].commodityId].quantity
									arrList[key].numberOfShippingBoxes = (arrList[key].quantity * 1 / this.obj[arrList[key].commodityId].quantity.toBox * 1).toFixed(3)
								}
							}		
						}
					}else if (num == 3) {
						for (let index in arrList) {
							if(arrList[index].type == 0){
								arrList[index].countSelectPrice = [{
										value: 0,
										label: '单价：' + this.obj[arrList[index].commodityId].price.unitPrice + '元'
									},
									{
										value: 1,
										label: '折箱单价：' + this.obj[arrList[index].commodityId].price.boxConversionUnitPrice + '元'
									},
									{
										value: 2,
										label: '折吨单价：' + this.obj[arrList[index].commodityId].price.tonConversionUnitPrice + '元'
									}
								]
							}else{
								arrList[index].countSelectPrice = [
									{
										value: 0,
										label: '折箱单价：' + this.obj[arrList[index].commodityId].price.boxConversionUnitPrice + '元'
									}
								]
							}
							arrList[index].conPrice = this.obj[arrList[index].commodityId].price
							arrList[index].conQuantity = this.obj[arrList[index].commodityId].quantity
							arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / this.obj[arrList[index].commodityId].quantity.toBox * 1).toFixed(3)
						}
					}
					this.countPrice(num)
					this.$forceUpdate()
				})
			},
			//库存单件// 计算商品箱数
			unitSinglePriceChange(num, index, count) {
				let arrList = []
				if (num == 0) {
					arrList = this.form.goods
				} else if (num == 1) {
					arrList = this.form.gift
				}
				if (count) {
					arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
						.toBox * 1).toFixed(3)
				} else {
					// for (let index in arrList) {
					if (arrList[index].unitSinglePrice == 0 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].conPrice.unitPrice
						arrList[index].factoryPrice = arrList[index].conPrice.unitPrice
					} else if (arrList[index].unitSinglePrice == 1 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].conPrice.boxConversionUnitPrice
						arrList[index].factoryPrice = arrList[index].conPrice.boxConversionUnitPrice
						// if(num == 0){
						// 	arrList[index].numberOfShippingBoxes = arrList[index].quantity
						// }
					} else if (arrList[index].unitSinglePrice == 2 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].conPrice.tonConversionUnitPrice
						arrList[index].factoryPrice = arrList[index].conPrice.tonConversionUnitPrice
						// if(num == 0){
						// 	arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 * arrList[index].conQuantity.toTon * 1).toFixed(2)
						// }
					}
					// }
				}

				// if (count) {
				// 	arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
				// 		.toBox * 1).toFixed(2)
				// }
				// }
				// if (num == 0 && count && arrList[index].unitSinglePrice != 1 || num == 1 && count && arrList[index].unitSinglePrice != 0) {
				// 	arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
				// 		.toBox * 1).toFixed(2)
				// }else{
				// 	arrList[index].numberOfShippingBoxes = arrList[index].quantity * 1
				// }

				this.countPrice()
				this.$forceUpdate()
			},
			//箱数量改变
			numberOfShippingBoxesChange(num, index) {
				let arrList = []
				if (num == 1) {
					arrList = this.form.goods
				} else {
					arrList = this.form.gift
				}
				// for (let index in arrList) {
				// if (arrList[index].unitSinglePrice == 0) {
				// 	arrList[index].unitPrice = arrList[index].factoryPrice
				// 	// 箱价conQuantity tobox
				// } else if (arrList[index].unitSinglePrice == 1) {
				// 	arrList[index].unitPrice = arrList[index].boxConversionUnitPrice
				// 	// arrList[index].numberOfShippingBoxes = arrList[index].quantity
				// } else if (arrList[index].unitSinglePrice == 2) {
				// 	arrList[index].unitPrice = arrList[index].tonConversionUnitPrice
				// 	// arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 / arrList[index].conQuantity.toTon * 1).toFixed(2)
				// }
				// arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 * arrList[index].conQuantity.toBox * 1)
				// 	.toFixed(2)
				// }
				// if (num == 1 && arrList[index].unitSinglePrice != 1 || num == 2 && arrList[index].unitSinglePrice != 0) {
				// 	arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 * arrList[index].conQuantity.toBox * 1)
				// 		.toFixed(2)
				// }else{
				// 	arrList[index].quantity = arrList[index].numberOfShippingBoxes * 1
				// }
				arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 * arrList[index].conQuantity.toBox * 1)
					.toFixed(2)
				this.countPrice()
			},
			// 关联商品计算溢价/合计
			countPrice(num) {
				// 计算溢价
				let yjPrice = 0
				let total = 0 //总价
				for (let key in this.form.goods) {
					this.form.goods[key].subtotal = this.form.goods[key].unitPrice * 1 * this.form.goods[key].quantity * 1
					total += (this.form.goods[key].unitPrice * 1 * this.form.goods[key].quantity * 1)
					if(this.form.goods[key].unitSinglePrice == 0){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.unitPrice * 1)*this.form.goods[key].quantity*1
					}else if(this.form.goods[key].unitSinglePrice == 1){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.boxConversionUnitPrice * 1)*this.form.goods[key].quantity*1
					}else if(this.form.goods[key].unitSinglePrice == 2){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.tonConversionUnitPrice * 1)*this.form.goods[key].quantity*1
					}
				}
				this.yjPrice = yjPrice
				this.hjPrice = total.toFixed(2)
				if (this.form.paymentType == '1001') {
					this.disabledAmount = false
				} else {
					this.disabledAmount = true
					//3：详情，读取接口返回，不做计算
					if(num != 3){
						// 付款金额
						this.form.depositAmount = this.hjPrice
					}
				}
				if(num != 3){
					//订单金额
					this.orderTotalAmount = total.toFixed(2)
					//订单差值
					this.form.differenceAmount = Math.abs(this.orderTotalAmount*1 -  total*1).toFixed(2)
				}
				// this.$forceUpdate()
			},
			// 计算订单金额
			countOrderAmount(num) {
				let price = 0
				if (num == 2) {
					for (let key in this.form.gift) {
						//库存单价
						if (this.form.gift[key].unitSinglePrice == 0 && this.form.gift[key].unitPrice * 1 < this.form.gift[
								key].conPrice.unitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.gift[key].unitSinglePrice == 1 && this.form.gift[key].unitPrice * 1 < this
							.form.gift[key].conPrice.boxConversionUnitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.gift[key].unitSinglePrice == 2 && this.form.gift[key].unitPrice * 1 < this
							.form.gift[key].conPrice.tonConversionUnitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						}
					}
				} else {
					for (let key in this.form.goods) {
						// price+=this.form.goods[key].unitPrice*1*this.form.goods[key].quantity*1
						if (this.form.goods[key].unitSinglePrice == 0 && this.form.goods[key].unitPrice * 1 < this.form
							.goods[key].conPrice.unitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.goods[key].unitSinglePrice == 1 && this.form.goods[key].unitPrice * 1 < this
							.form.goods[key].conPrice.boxConversionUnitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.goods[key].unitSinglePrice == 2 && this.form.goods[key].unitPrice * 1 < this
							.form.goods[key].conPrice.tonConversionUnitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						}
					}
					// this.form.orderTotalAmount = price
				}
				this.$forceUpdate()
			},
			//预估收益
			countPriceGoods() {
				//没有选择商品切换
				if (this.form.goods.length == 0) {
					this.$modal.msgError('请先选择商品')
					return false;
				}
				for (let key in this.form.goods) {
					if (
						!this.form.goods[key].quantity ||
						!this.form.goods[key].unitPrice ||
						this.form.goods[key].quantity * 1 == 0 ||
						this.form.goods[key].unitPrice * 1 == 0
					) {
						this.$modal.msgError('请先补全销售单价/数量')
						return false;
					}
				}
				// 计算提成
				this.getFnRoyalties(1)
			},
			//计算提成
			getFnRoyalties(num) {
				let data = {
					list: this.form.goods.concat(this.form.gift),
					orderTotalAmount:this.orderTotalAmount,
					areaCode: this.areaCode, //地区编码
					logisticsId: this.logisticsId, //物流id
				}
				fnRoyalties(data).then(res => {
					if (num == 1) {
						this.isCanGift = res.data.isCanGift
						if (res.data.isCanGift == false) {
							this.$modal.msgError('暂无赠品')
							return false;
						}
					} else {
						return res.data.isCanGift
					}
				})
			},
			//选中赠品
			selectGift(e) {
				this.getGoodsGroupList(e, 1)
			},
			//删除关联商品
			delGoods(index) {
				this.form.goods.splice(index, 1)
			},
			//删除赠品
			delGift(index) {
				this.form.gift.splice(index, 1)
			},
			// 关联商品价格联动
			unitPriceChange(value, index) {
				this.form.goods[index].unitPrice = value
				//选择
				let price = 0
				for (let key in this.form.goods) {
					if (this.form.goods[key].unitSinglePrice == 0) {
						price += this.form.goods[key].unitPrice * 1 - this.form.goods[key].factoryPrice * 1
					}
				}
				this.yjPrice = price
				this.countPrice(1)
			},
			//关联商品数量联动
			quantityChange(num, index) {
				this.countPrice()
				// 数字1:计算箱数量
				this.unitSinglePriceChange(num, index, 1)
			},
			//赠品数量联动
			quantityChange1(num, index) {
				// 数字1:计算箱数量
				this.unitSinglePriceChange(num, index, 1)
			},
			// 赠品价格联动
			unitPriceChange1(value, index) {
				this.form.gift[index].unitPrice = value
				this.form.gift[index].subtotal = this.form.gift[index].unitPrice * 1 * this.form.gift[index].quantity * 1
			},
			// // 添加商品添加赠品
			// handleAdd(url) {
			// 	localStorage.setItem('form',JSON.stringify(this.form))
			// 	this.$router.push(url)
			// },
			// 计算毛利率
			countRate() {
				// let goodsArr = this.form.goods.concat(this.form.gift)
				let goodsArr = this.form.goods
				let goodsArr1 = this.form.goods.concat(this.form.gift)
				let data = {
					list: goodsArr,
					areaCode:this.areaCode,
					logisticsId:this.logisticsId,
					orderTotalAmount:this.orderTotalAmount
				}
				for (let key in goodsArr) {
					if (goodsArr[key].unitPrice <= 0 || goodsArr[key].unitPrice == '') {
						this.$modal.msgError('请填写销售单价')
						return false
					}
				}
				for (let key in goodsArr1) {
					if (goodsArr[key].quantity <= 0 || goodsArr[key].quantity == '') {
						this.$modal.msgError('请填写数量')
						return false
					}
				}
				
				fnRoyalties(data).then(res => {
					this.dialogVisible = true
					let data = res.data
					this.result[0] = {
						orderTotalAmount: data.orderTotalAmount,
						inventoryCosts: data.inventoryCosts,
						realTimeCosts: data.realTimeCosts,
						inventoryGrossProfitRate: data.inventoryGrossProfitRate,
						realTimeProfitRate: data.realTimeProfitRate
					}
				})
			},
			close() {
				this.dialogVisible = false
			}
		}
	}
</script>

<style>
</style>